﻿using UnityEngine;

public class Checkpoint : MonoBehaviour
{
    private EventSystem cEventSystem;
    private SceneController sceneController;
    private SaveManager saveManager;
    private SpriteRenderer m_spriteRenderer;
    private CheckpointManager checkpointsManager;

    private bool _Active;   //记录点是否被激活
    public bool Active 
    {
        get => _Active;
        set
        {
            if (_Active == value)
                return;
            if (value)
            {
                m_spriteRenderer.color = Color.green;
                saveManager.UpdateScene(sceneController.Index, checkpointsManager.GetCheckPointIndex(this));
            }
            else
            {
                m_spriteRenderer.color = Color.red;
            }
            _Active = value;
        }
    }

    private void Awake()
    {
        cEventSystem = Service.Get<EventSystem>();
        sceneController = Service.Get<SceneController>();
        saveManager = Service.Get<GameManager>().saveManager;
        checkpointsManager = GetComponentInParent<CheckpointManager>();
        m_spriteRenderer = GetComponent<SpriteRenderer>();
    }

    private void OnEnable()
    {
        cEventSystem.PlayerDie += OnPlayerDie;
        cEventSystem.AfterSceneLoad += OnAfterSceneLoad;
        cEventSystem.TouchCheckPoint += OnTouchCheckPoint;
    }
    private void OnDisable()
    {
        cEventSystem.PlayerDie -= OnPlayerDie;
        cEventSystem.AfterSceneLoad -= OnAfterSceneLoad;
        cEventSystem.TouchCheckPoint -= OnTouchCheckPoint;
    }

    public void Spawn()
    {
        Character.Instance.Spawn(transform.position);
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.GetComponent<Character>() != null)
        {
            cEventSystem.TouchCheckPoint?.Invoke(this);
        }
    }

    private void OnTouchCheckPoint(Checkpoint checkpoint)
    {
        if (checkpoint != this)
            Active = false;
        else
            Active = true;
    }
    private void OnPlayerDie()
    {
        if (Active)
            Spawn();
    }
    private void OnAfterSceneLoad(int sceneIndex)
    {
        if (Active) 
            Spawn();
    }
}
